import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import 'rxjs/add/operator/toPromise';
import {PathInfo, PathInfoPage, GetLogicInfo} from './getLogic';
import {LogicAdminService} from '../logicAdmin/logicAdmin.service';
import {UserService} from '../user/user.service';
import {Router} from '@angular/router';

@Injectable()
export class GetLogicService {
  public token: string;
  public nodeId: string;
  public fileId: string;
  public type: string;
  public mapId: string;
  private hostUrl = ParamConfig.HTTP_WEB_HOST_URL + 'logicNode/getLogicNodeById'; // URL to web api
  private hostUrlgetreal = ParamConfig.HTTP_WEB_HOST_URL + 'realNode/getRealNodeData'; // 物理基点查询
  private hostUrlgetPath = ParamConfig.HTTP_WEB_HOST_URL + 'path/getPathData'; // URL to web api
  private hostUrlUpdateLogic = ParamConfig.HTTP_WEB_HOST_URL + 'logicNode/updateLogicNode'; // 修改
  private hostUrlDeleteLogic = ParamConfig.HTTP_WEB_HOST_URL + 'rbFile/fileDeleteByid'; // 删除图片
  constructor(private http: Http, private logicAdminService: LogicAdminService, private userService: UserService, private router: Router) {
  }
// 查询NodeId
  getNodeIdInfo(): Promise<any> {
    this.nodeId = this.logicAdminService.sendNodeId();
    const request = JSON.stringify({
      nodeId: this.nodeId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrl, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return [true, body.logicNodeTO];
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 查询物理基点
  getReal(): Promise<any> {
    const request = JSON.stringify({
      mapId: this.mapId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlgetreal, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return [true, body.datas];
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 查询路径
  getPath(page): Promise<any> {
    const request = JSON.stringify({
      rows: '10000',
      page: page,
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlgetPath, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            const pagedata = new PathInfoPage();
            pagedata.pathInfo = body as PathInfo[];
            pagedata.totalPages = body.total;
            return pagedata;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

// 修改
  updateLogicInfo(getLogicInfo: GetLogicInfo, fileId): Promise<any> {
    const request = JSON.stringify({
      nodeId: this.nodeId,
      name: getLogicInfo.name,
      realNodeId: getLogicInfo.realNodeId,
      sort: getLogicInfo.sort,
      pathId: getLogicInfo.pathId,
      eventId: getLogicInfo.eventId,
      fileId: fileId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlUpdateLogic, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  // 删除图片
  deleteLogicImageinfo(fileIdImage): Promise<any> {
    const request = JSON.stringify({
      nodeId: this.nodeId,
      fileId: fileIdImage,
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlDeleteLogic, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
